#include "gd32f30x.h"
#include "usart.h"
#include <stdio.h>

void usart_init() {
    /* enable GPIO clock */
    rcu_periph_clock_enable(RCU_GPIOA);

    /* enable USART clock */
    rcu_periph_clock_enable(RCU_USART0);

    /* connect port to USARTx_Tx */
    gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);

    /* connect port to USARTx_Rx */
    gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_10);

    /* USART configure */
    usart_deinit(USART0);
    usart_baudrate_set(USART0, 115200U);
    usart_receive_config(USART0, USART_RECEIVE_ENABLE);
    usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
    usart_enable(USART0);
}

int _write(int fd, char *ptr, int len)  
{  
    for (int i=0; i<len; i++) {
        usart_data_transmit(USART0, (uint8_t)ptr[i]);
        while (RESET == usart_flag_get(USART0, USART_FLAG_TBE));
    }
    /* wait for completion of USART transmission */
    while(RESET == usart_flag_get(USART0, USART_FLAG_TC)){
    }
    return len;
}
